package com.tj.interceptor;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tj.utils.JwtUtil;

import java.io.IOException;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @SneakyThrows
    private void setResponse(HttpServletResponse response) {
        response.setContentType("text/text;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("TOKEN_ERR");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //所有的 OPTIONS 请求统统放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return true;
        }

        //1.获取请求头携带的token
        String token = request.getHeader("authorization");

        //2.判断token是否为空
        if(StrUtil.isBlank(token)) {
            log.info("token为空");
            setResponse(response);
            return false;
        }

        //3.验证token
        try {
            Claims claims = JwtUtil.parseJWT(token);
        }catch (Exception e) {
            log.info("验证token失败");
            // e.printStackTrace();
            setResponse(response);
            return false;
        }
        log.info("验证token成功");

        //3.验证通过，放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
